﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BrnMall.Manager.Domain.BusinessCard;
using BrnMall.Manager.Manager.BusinessCard;
using BrnMall.Services;
using PetaPoco;
using QIDong.WeApp.Models;
using WeiTap.Restful;
using BrnMall.Manager.Manager.AddressBook;
using BrnMall.Manager.Domain.Rander;
using BrnMall.Services.WJK;
using System.Text;
using BrnMall.Manager.Manager.Radar;

namespace QIDong.WeApp.Controllers
{
    /// <summary>
    /// 用户名片
    /// </summary>
    public class BusinessCardController : WebApi
    {
        #region Ai名片

        /// <summary>
        /// 获取客户名片列表
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public object GetAiCardList(int uid, int page = 1, int pageSize = 50)
        {
            var staffId = new StringBuilder();
            //客户列表
            var clientList = ClientManager.GetListByUid(uid);
            clientList.ForEach(x => staffId.Append($",{x.Staffid}"));

            if (staffId.Length < 1)
                return null;

            //名片列表
            var staffList = StaffManager.GetListByIds(staffId.ToString().Substring(1));
            var list = new List<StaffCardModel>();

            foreach (var item in staffList)
            {
                //员工实体
                var client = clientList.Find(x => x.Staffid == item.Id);
                var source = client.Source == 1 ? "扫码" : "转发";
                var staff = new StaffCardModel()
                {
                    Id = item.Id,
                    Position = item.Position,
                    Avater = item.Avater,
                    Company = item.Company,
                    Email = item.Email,
                    Mobile = item.Mobile,
                    MobileState = item.MobileState,
                    Name = item.Name,
                    No = list.Count + 1,
                    AddTime = client.Addtime, //客户创建时间
                    Source = source,
                    DisplayState = client != null ? client.DisplayState : 1
                };
                list.Add(staff);
            }
            return list;
        }

        /// <summary>
        /// 获取AI名片和标签，并更新浏览数
        /// </summary>
        /// <param name="staffId">销售员名片ID</param>
        /// <param name="uid">客户uid</param>
        /// <returns></returns>
        public object GetAiCardDetail(int staffId, int uid)
        {
            var staff = StaffManager.Get(staffId);
            if (staff == null)
                throw new Exception("找不到记录");

            var model = new
            {
                CardInfo = staff,
                TagList = StaffTagManager.GetList(staffId)
            };

            //更新次数
            StaffManager.UpdateClickCount(staffId);
            return model;
        }

        /// <summary>
        /// 获取AI名片
        /// </summary>
        /// <param name="staffId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public object GetAiCard(int staffId, int uid)
        {
            var staff = StaffManager.Get(staffId);
            if (staff == null)
                throw new Exception("找不到记录");

            var model = new
            {
                CardInfo = staff
            };
            return model;
        }

        /// <summary>
        /// 名片点赞
        /// </summary>
        /// <param name="staffId">名片ID</param>
        /// <param name="uid">操作人uid</param>
        /// <returns></returns>
        public bool AddCardUp(int staffId, int uid)
        {
            //var staff = StaffManager.Get(staffId);
            //if (staff == null)
            //    throw new Exception("找不到记录");

            if (StaffManager.UpdateUpCount(staffId))
            {
                ActionRecords.AddCardUpRecord(uid, staffId);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 名片标签点赞
        /// </summary>
        /// <param name="tagId"></param>
        /// <param name="staffId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool AddTagUp(int tagId, int staffId, int uid)
        {
            if (StaffTagManager.UpdateUpCount(tagId))
            {
                ActionRecords.AddTagUpRecord(uid, staffId);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 个性签名点赞
        /// </summary>
        /// <param name="staffId">名片ID</param>
        /// <param name="uid">登录会员的uid</param>
        /// <returns></returns>
        public bool AddSignUp(int staffId, int uid)
        {
            //var staff = StaffManager.Get(staffId);
            //if (staff == null)
            //    throw new Exception("找不到记录");

            if (StaffManager.UpdateSignUpCount(staffId))
            {
                ActionRecords.AddSignUpRecord(uid, staffId);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 修改名片显示状态
        /// </summary>
        /// <param name="staffId">名片ID</param>
        /// <param name="uid">登录会员uid</param>
        /// <param name="state">状态（1 正常显示, 2 屏蔽）</param>
        /// <returns></returns>
        public bool UpdateDisplayState(int staffId, int uid, int state)
        {
            var staff = StaffManager.Get(staffId);
            if (staff == null)
                throw new Exception("找不到记录");

            if (ClientManager.UpdateDisplayState(staffId, uid, state))
            {
                ActionRecords.AddSignUpRecord(uid, staffId);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 修改客户来源,不存在时，自动创建增客户
        /// </summary>
        /// <param name="staffId">名片ID</param>
        /// <param name="uid">登录会员uid</param>
        /// <param name="source">客户来源(1 扫码, 2 转发)</param>
        /// <returns></returns>
        public bool UpdateSource(int staffId, int uid, int source)
        {
            var model = ClientManager.GetByUid(uid, staffId);
            if (model == null)
            {
                var user = Users.GetPartUserById(uid);
                var staff = StaffManager.Get(staffId);
                model = new BrnMall.Manager.Domain.AddressBook.Clients()
                {
                    Uid = user.Uid,
                    Staffid = staffId,
                    MemoName = user.NickName,
                    Company = staff.Company,
                    Avatar = user.Avatar,
                    DisplayState = 1,
                    Sex = 0,
                    Source = source,
                    Probability = 0,
                    Birthday = DateTime.Now,
                    FollowTime = DateTime.Now,
                    ActiveTime = DateTime.Now,
                    tradeDate = "",
                    Addtime = DateTime.Now
                };
                return ClientManager.Insert(model);
            }
            else
                return ClientManager.UpdateSource(staffId, uid, source);
        }

        /// <summary>
        /// 记录会员的操作
        /// </summary>
        /// <param name="staffId">名片ID</param>
        /// <param name="uid">会员ID</param>
        /// <param name="actionType">会员的操作(0 查看商品, 1 查看官网, 2 转发名片, 3 复制微信, 4 查看名片, 5 查看动态, 7 保存电话, 9 拨打电话, 12 复制邮箱, 13 转发动态, 16 拨打手机)</param>
        /// <returns></returns>
        public bool AddAiCardAction(int staffId, int uid, int actionType)
        {
            var model = new ActionRecord()
            {
                Uid = uid,
                StaffId = staffId,
                ActionType = actionType,
                Addtime = DateTime.Now,
                DateNumber = Convert.ToInt32(DateTime.Now.ToString("yyyyMMdd"))
            };

            if (actionType == 2)
                StaffManager.UpdateShareCount(staffId);

            return ActionRecords.AddActionRecord(model);
        }

        #endregion


        #region 名片
        /// <summary>
        /// 添加名片信息，如果名片存在，则只更新名片编号
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="storeId">店铺编号</param>
        /// <param name="cardCode">名片编号</param>
        /// <returns></returns>
        public bool AddOrUpdateUserCard(int uid, int storeId, string cardCode)
        {

            var card = UserCardManager.GetUserCard(uid);
            if (card == null)
            {
                card = new UserCard
                {
                    CardCode = cardCode,
                    Favorite = 0,
                    CId = 0,
                    Praised = 0,
                    StoreId = storeId,
                    UId = uid,
                    Views = 0,
                    IsVerify = false
                };
                UserCardManager.InsertUserCard(card);
                return true;
            }
            UserCardManager.UpdateCardCode(card.CId, cardCode);
            return true;

        }


        /// <summary>
        /// 获取用户的名片信息
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public UserCardModel GetUserCard(int uid,int storeId)
        {
            var card= UserCardManager.GetUserCard(uid);
            if (card == null)
            {
                card = new UserCard
                {
                    CardCode= "card001",
                    Favorite=0,
                    IsVerify=false,
                    Praised=0,
                    StoreId=storeId,
                    UId=uid,
                    Views=0
                };
                UserCardManager.InsertUserCard(card);
            }
            ;
            return new UserCardModel
            {
                CardCode=card.CardCode,
                CId=card.CId,
                Favorite=card.Favorite,
                Praised=card.Praised,
                StoreId=card.StoreId,
                User=Users.GetUserById(card.UId),
                Views=card.Views,
                IsVerify = card.IsVerify
            };
        }

        /// <summary>
        /// 操作名片，查看，收藏，点赞
        /// </summary>
        /// <param name="cid">名片ID</param>
        /// <param name="actionUid">操作人</param>
        /// <param name="actionType">动作类型0：未知，1：点赞，2：收藏，3：查看</param>
        /// <returns></returns>
        public bool AddUserCardAction(int cid, int actionUid, int actionType)
        {
            var action = new CardAction
            {
                ActionTime = DateTime.Now,
                ActionType = actionType,
                ActionUId = actionUid,
                CId = cid,
                Id = 0
            };
            if (actionType == 3)
                UserCardManager.InsertCardAction(action);
            else
            {
                var act = UserCardManager.GetCardAction(cid, actionUid, actionType);
                if (act == null)
                    UserCardManager.InsertCardAction(action);
            }
            return true;
        }

        /// <summary>
        /// 检查用户是否对此名片执行过相关操作
        /// </summary>
        /// <param name="cid">名片ID</param>
        /// <param name="uid">用户ID</param>
        /// <param name="actionType">动作类型0：未知，1：点赞，2：收藏，3：查看</param>
        /// <returns></returns>
        public bool CheckUserAction(int cid, int uid,int actionType)
        {
            var act = UserCardManager.GetCardAction(cid, uid, actionType);
            return act != null;
        }
        /// <summary>
        /// 删除用户对此名片执行过相关操作
        /// </summary>
        /// <param name="cid">名片ID</param>
        /// <param name="uid">用户ID</param>
        /// <param name="actionType">1：点赞，2：收藏</param>
        public bool DeleteUserAction(int cid, int uid, int actionType)
        {
            var act = UserCardManager.GetCardAction(cid, uid, actionType);
            if (act == null) return false;
            UserCardManager.DeleteCardAction(act);
            return true;
        }

        /// <summary>
        /// 获取用户点赞，查看，收藏的名片信息
        /// </summary>
        /// <param name="uid">用户ID</param>
        /// <param name="actionType">0：未知，1：点赞，2：收藏，3：查看</param>
        /// <param name="pageNumber">当前页码</param>
        /// <param name="itemsPerPage">每页多少条，默认15</param>
        /// <returns></returns>
        public Page<UserCardModel> GetUserActionCards(int uid,int actionType, long pageNumber, long itemsPerPage = 15)
        {
            var cards = UserCardManager.GetUserActionCard(uid,actionType, pageNumber, itemsPerPage);
            var result = new Page<UserCardModel>
            {
                CurrentPage = cards.CurrentPage,
                Items = cards.Items.Select(t => new UserCardModel
                {
                    CardCode = t.CardCode,
                    CId = t.CId,
                    Favorite = t.Favorite,
                    Praised = t.Praised,
                    StoreId = t.StoreId,
                    User = Users.GetUserById(t.UId),
                    Views = t.Views,
                    IsVerify = t.IsVerify
                }).ToList(),
                ItemsPerPage = cards.ItemsPerPage,
                TotalItems = cards.TotalItems,
                TotalPages = cards.TotalPages
            };
            return result;
        }

        /// <summary>
        /// 获取名片的详细信息
        /// </summary>
        /// <param name="cid">名片ID</param>
        /// <param name="actionType">动作类型0：未知，1：点赞，2：收藏，3：查看</param>
        /// <param name="pageNumber">当前页码</param>
        /// <param name="itemsPerPage">每页多少条</param>
        /// <returns></returns>
        public Page<CardActionModel> GetCardActionPage(int cid, int actionType, long pageNumber = 1,
            long itemsPerPage = 15)
        {
            var result = UserCardManager.GetCardActionPage(cid, actionType, pageNumber, itemsPerPage);
            var newItems = result.Items.Select(t => new CardActionModel
            {
                ActionTime = t.ActionTime,
                ActionType = t.ActionType,
                ActionUser = Users.GetUserById(t.ActionUId),
                CId = t.CId,
                Id = t.Id
            }).ToList();
            return new Page<CardActionModel>
            {
                CurrentPage = result.CurrentPage,
                Items = newItems,
                ItemsPerPage = itemsPerPage,
                TotalItems = result.TotalItems,
                TotalPages = result.TotalPages
            };
        }
        #endregion

        #region 标签
        /// <summary>
        /// 获取系统内置印象标签
        /// </summary>
        /// <param name="tagtype">0：未知， 1：男，2：女</param>
        /// <returns></returns>
        public IList<Tag> GetTags(int tagtype)
        {
            return UserTagManager.GetTags(tagtype);
        }

        /// <summary>
        /// 获取用户的印象标签
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="top">获取签名几条，-1代表所有</param>
        /// <returns></returns>
        public IList<UserTag> GetUerTags(int uid, int top = -1)
        {
            return UserTagManager.GetUserTags(uid, top);
        }
        /// <summary>
        /// 获取用户标签的详情
        /// </summary>
        /// <param name="userTagId">标签ID</param>
        /// <param name="pageNumber">当前页</param>
        /// <param name="itemsPerPage">每页多少条</param>
        /// <returns></returns>

        public Page<UserTagHitModel> GetUserTagHit(int userTagId, long pageNumber, long itemsPerPage)
        {
            var result = UserTagManager.GetUserTagHitPage(userTagId, pageNumber, itemsPerPage);
            var newItems = result.Items.Select(t => new UserTagHitModel
            {
                HitTime = t.HitTime,
                HitUser = Users.GetPartUserById(t.HitUid),
                Id = t.Id,
                UserTagId = t.UserTagId
            }).ToList();
            return new Page<UserTagHitModel>
            {
                CurrentPage = result.CurrentPage,
                Items = newItems,
                ItemsPerPage = result.ItemsPerPage,
                TotalItems = result.TotalItems,
                TotalPages = result.TotalPages
            };
        }

        /// <summary>
        /// 添加用户标签印象
        /// </summary>
        /// <param name="uid">被添加人ID</param>
        /// <param name="hitUid">执行添加的人ID</param>
        /// <param name="tagid">系统标签ID，如果是自己添加的则为0</param>
        /// <param name="name">标签名称</param>
        /// <returns></returns>
        public bool AddUserTag(int uid, int hitUid, int tagid = 0, string name = "")
        {
            var oldTag = UserTagManager.GetUserTagByName(uid, name);
            if (oldTag == null)
            {
                oldTag = new UserTag
                {
                    Uid = uid,
                    TagId = tagid,
                    HitCount = 0,
                    Name = name
                };
                UserTagManager.InsertUserTag(oldTag);
            }
            
            var tagHit = new UserTagHit
            {
                UserTagId = oldTag.Id,
                HitUid = hitUid,
                HitTime = DateTime.Now
            };
            UserTagManager.InsertUserTagHit(tagHit);
            return true;
        }
        /// <summary>
        /// 批量添加系统标签
        /// </summary>
        /// <param name="tags"></param>
        /// <returns></returns>
        public bool BatchAddUserTag(BatchAddUserCardDto tags)
        {
            if (tags == null) return false;
            foreach (var tag in tags.Tags)
            {
                UserTagManager.InsertUserTag(tag);
                var tagHit = new UserTagHit
                {
                    UserTagId = tag.Id,
                    HitUid = tag.Uid,
                    HitTime = DateTime.Now
                };
                UserTagManager.InsertUserTagHit(tagHit);
            }
            return true;
        }

        #endregion

        #region 相册
        /// <summary>
        /// 获取用户的相册日志
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pageNumber"></param>
        /// <param name="itemsPerPage"></param>
        /// <returns></returns>
        public Page<TimeLineModel> GetUserTimeLinePage(int uid, long pageNumber, long itemsPerPage)
        {
            var result = TimeLineManager.GetUserTimeLine(uid, pageNumber, itemsPerPage);
            var newTimes = result.Items.Select(t => new TimeLineModel
            {
                TimeLine = t,
                TimeLineImgs = TimeLineManager.GeTimeLineImgs(t.Id)
            }).ToList();
            return new Page<TimeLineModel>
            {
                CurrentPage = result.CurrentPage,
                Items = newTimes,
                ItemsPerPage = result.ItemsPerPage,
                TotalItems = result.TotalItems,
                TotalPages = result.TotalPages
            };
        }
        /// <summary>
        /// 新增用户图册
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="storeId">店铺编号</param>
        /// <param name="message">图册说明</param>
        /// <param name="imgs">图册地址</param>
        public void InsertTimeline(int uid, int storeId, string message, IList<TimeLineImg> imgs)
        {
            var timeLine = new TimeLine
            {
                CreateTime = DateTime.Now,
                Message = message,
                StoreId = storeId,
                Uid = uid
            };
            TimeLineManager.InsertTimeLine(timeLine);
            foreach (var img in imgs)
            {
                img.TId = timeLine.Id;
                TimeLineManager.InsertTimelineImg(img);
            }
        }
        /// <summary>
        /// 获取用户最新的图册记录
        /// </summary>
        /// <param name="uid">用户ID</param>
        /// <param name="top">前多少条记录</param>
        /// <returns></returns>
        public IList<TimeLineImg> GetUserTimeLineImgs(int uid, int top = 1)
        {
            return TimeLineManager.GetUserTimeLineImgs(uid, top);
        }
        /// <summary>
        /// 删除图册记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteUserTimeLine(int id)
        {
            TimeLineManager.DeleteTimeLine(id);
            return true;
        }

        #endregion

        #region 认证资料
        /// <summary>
        /// 上传认证资料
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="storeid"></param>
        /// <param name="verifytype"></param>
        /// <param name="verifyimg"></param>
        public void UploadVerifyImg(int uid, int storeid, int verifytype, string verifyimg)
        {
            var verify = new CardVerify
            {
                StoreId = storeid,
                UId = uid,
                VerifyImg = verifyimg,
                VerifyType = verifytype,
                VerifyState = 1,
                VerifyTime = new DateTime(1900,1,1),
                VerifyUid = 0
            };
            UserCardManager.AddCardVerify(verify);
        }
        /// <summary>
        /// 获取用户的认证资料
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public CardVerify GetUserVerify(int uid)
        {
            return UserCardManager.GetCardVerifyByUId(uid);
        }

        #endregion
    }
}
